package com.suntimes.guangjiegou.component;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.suntimes.cl.util.CLLog;
import com.suntimes.cl.util.CLStringUtil;
import com.suntimes.guangjiegou.R;

public class GroupLayout extends LinearLayout implements OnClickListener {
	
	public static final String TAG = "GroupLayout";
	
	private String title;
	
	private OnItemClickListener mListener;
	private int mChildCount;
	
	public GroupLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.setOrientation(LinearLayout.VERTICAL);
		
		TypedArray typeArray = context.obtainStyledAttributes(attrs, R.styleable.GroupLayout);
		title = typeArray.getString(R.styleable.GroupLayout_title);
		typeArray.recycle();
		
		initView();
	}
	
	private void initView() {
		if(!CLStringUtil.isEmptyString(title)) {
			TextView txtTitle = new TextView(getContext());
			txtTitle.setTextColor(Color.GRAY);
			txtTitle.setText(title);
			txtTitle.setTag(Integer.valueOf(-1));
			super.addView(txtTitle);
			
			View view = new View(getContext());
			view.setTag(Integer.valueOf(-1));
			view.setBackgroundResource(R.drawable.title_line);
			super.addView(view);
		} else {
			View view = new View(getContext());
			view.setTag(Integer.valueOf(-1));
			view.setBackgroundResource(R.color.gray);
			this.addView(view, new LayoutParams(LayoutParams.MATCH_PARENT, 1));
		}
	}

	@Override
	public void addView(View child, int index, ViewGroup.LayoutParams params) {
		super.addView(child, index, params);
		
		Integer tag = ((Integer)child.getTag());
		if(tag == null) {
			child.setTag(Integer.valueOf(mChildCount));
			child.setBackgroundResource(R.drawable.group_table_item);
			mChildCount ++;
			child.setOnClickListener(this);
			
			View view = new View(getContext());
			view.setTag(Integer.valueOf(-1));
			view.setBackgroundResource(R.color.gray);
			this.addView(view, new LayoutParams(LayoutParams.MATCH_PARENT, 1));
		} 
		
		CLLog.i(TAG, "addView index >> " + index);
	}

	public void setOnItemClickListener(OnItemClickListener listener) {
		mListener = listener;
	}
	
	

	@Override
	public void onClick(View view) {
		if(mListener != null) {
			int position = ((Integer)view.getTag()).intValue();
			mListener.onItemClick(this, view, position);
		}
	}
	
	public interface OnItemClickListener {
		public void onItemClick(GroupLayout groupLayout, View item, int position);
	}

}
